package model

import (
	"aglaia/global"
	"errors"
	"github.com/jinzhu/gorm"
	"time"
)

type AuthRecord struct {
	Model

	AuthId uint  `json:"auth_id"`
	Auth   *Auth `json:"auth"`

	IsSuccess bool `json:"is_success"`

	LastLoginIp string `json:"last_login_ip"`
}

func (a AuthRecord) TableName() string {
	return "auth_record"
}

var (
	ErrAuthRateLimit = errors.New("auth rate limit")
)

func (a *AuthRecord) Create(tx *gorm.DB) (surplus int, err error) {
	var (
		count     int
		timeLimit = 5
	)

	if err := tx.Table(a.TableName()).Where("created_at > ? and is_success = ?", time.Now().Add(-time.Hour*24), false).Limit(timeLimit).
		Order("id desc").Count(&count).Error; err != nil {
		global.Logger.Infof("auth_record.Count err: %v\n", err)
		tx.Rollback()
		return 0, err
	}

	if count >= 5 {
		if err := tx.Create(a).Error; err != nil {
			tx.Rollback()
			return 0, err
		}

		if err := tx.Commit().Error; err != nil {
			tx.Rollback()
			return 0, err
		}
		return timeLimit - count, ErrAuthRateLimit
	}

	if err := tx.Create(a).Error; err != nil {
		tx.Rollback()
		return 0, err
	}
	if err := tx.Commit().Error; err != nil {
		tx.Rollback()
		return 0, err
	}

	return timeLimit, nil
}
